<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>单词学习器</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { 
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            min-height: 100vh; padding: 20px; 
        }
        .container { 
            max-width: 400px; margin: 0 auto; background: white; 
            border-radius: 20px; box-shadow: 0 20px 40px rgba(0,0,0,0.1); 
            overflow: hidden; min-height: 80vh; 
        }
        .view { display: none; padding: 30px 20px; min-height: 80vh; flex-direction: column; }
        .view.active { display: flex; }
        h1 { text-align: center; margin-bottom: 30px; color: #333; font-size: 24px; }
        .group-list { flex: 1; }
        .group-item { 
            background: #f8f9fa; border: 2px solid #e9ecef; border-radius: 12px; 
            padding: 20px; margin-bottom: 15px; text-align: center; font-size: 18px; 
            font-weight: 600; color: #495057; cursor: pointer; transition: all 0.3s ease; 
        }
        .group-item:active { 
            background: #667eea; color: white; border-color: #667eea; transform: translateY(-2px); 
        }
        .menu-buttons { margin-top: 30px; }
        .progress-bar { 
            width: 100%; height: 6px; background: #e9ecef; border-radius: 3px; 
            margin-bottom: 10px; overflow: hidden; 
        }
        .progress-fill { 
            height: 100%; background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%); 
            border-radius: 3px; transition: width 0.3s ease; width: 0%; 
        }
        .word-view { display: none; flex: 1; flex-direction: column; justify-content: center; align-items: center; text-align: center; }
        .word-view.active { display: flex; }
        .play-indicator { font-size: 48px; margin-bottom: 20px; }
        .hint { font-size: 18px; color: #666; }
        .word { font-size: 36px; font-weight: bold; margin-bottom: 10px; color: #333; }
        .phonetic { font-size: 18px; color: #666; margin-bottom: 20px; font-family: monospace; }
        .meaning { font-size: 24px; color: #2c5530; margin-bottom: 25px; font-weight: 600; }
        .sentence { font-size: 18px; color: #555; font-style: italic; line-height: 1.5; margin-bottom: 30px; padding: 0 10px; }
        
        .difficult-btn, .prev-btn, .next-btn, .back-btn, .start-btn, .pause-btn { 
            padding: 15px; border: none; border-radius: 12px; 
            font-size: 16px; font-weight: 600; cursor: pointer; transition: all 0.3s ease; 
        }
        .difficult-btn { 
            background: #fff3cd; color: #856404; border: 2px solid #ffeaa7; 
            width: 100%; margin-top: 8px;
        }
        .difficult-btn.active { background: #f39c12; color: white; }
        .difficult-btn:disabled { background: #e9ecef; color: #6c757d; cursor: not-allowed; }
        
        .prev-btn { background: #6c757d; color: white; flex: 1; }
        .next-btn { background: #28a745; color: white; flex: 1; }
        .pause-btn { background: #ffc107; color: white; flex: 1; }
        .back-btn { background: #6c757d; color: white; width: 100%; margin-top: 8px; }
        .start-btn { background: #28a745; color: white; width: 100%; margin-top: 8px; }
        
        button:active { transform: scale(0.98); }
        
        .difficult-list { flex: 1; margin-bottom: 20px; }
        .difficult-word-item { 
            background: #f8d7da; border: 2px solid #f5c6cb; border-radius: 12px; 
            padding: 15px; margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center; 
        }
        .difficult-word-info { text-align: left; flex: 1; }
        .difficult-word { font-weight: bold; font-size: 18px; color: #721c24; }
        .difficult-meaning { color: #856404; font-size: 14px; }
        .remove-btn { 
            background: #dc3545; color: white; border: none; border-radius: 8px; 
            padding: 8px 12px; cursor: pointer; font-size: 12px; margin-left: 10px; 
        }
        .state-indicator {
            text-align: center;
            margin: 10px 0;
            padding: 8px;
            background: #f8f9fa;
            border-radius: 8px;
            font-size: 14px;
            color: #666;
            border: 1px solid #e9ecef;
        }
        .progress-info {
            text-align: center;
            color: #666;
            font-size: 14px;
            margin-bottom: 10px;
        }
        .controls {
            display: flex;
            flex-direction: column;
            gap: 8px;
            margin-top: 20px;
        }
        .nav-buttons {
            display: flex;
            gap: 10px;
            margin-bottom: 8px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div id="groupSelection" class="view active">
            <h1>选择学习分组</h1>
            <div id="groupList" class="group-list"></div>
            <div class="menu-buttons">
                <button id="reviewDifficultBtn" class="difficult-btn">复习生词本</button>
            </div>
        </div>

        <div id="learningView" class="view">
            <div class="progress-bar">
                <div class="progress-fill" id="progressFill"></div>
            </div>
            <div class="progress-info">
                进度: <span id="progressText">0/0</span>
            </div>
            <div class="state-indicator" id="stateIndicator">准备开始</div>
            
            <div id="blankView" class="word-view active">
                <div class="play-indicator">🔊 播放中...</div>
                <div class="hint">仔细听发音</div>
            </div>

            <div id="infoView" class="word-view">
                <div class="word" id="currentWord">apple</div>
                <div class="phonetic" id="currentPhonetic">[ˈæpl]</div>
                <div class="meaning" id="currentMeaning">苹果</div>
                <div class="sentence" id="currentSentence">I eat an apple every day.</div>
                <button id="difficultBtn" class="difficult-btn">标记为不熟悉</button>
            </div>

            <div class="controls">
                <div class="nav-buttons">
                    <button id="prevBtn" class="prev-btn">⬅️ 上一个</button>
                    <button id="pauseBtn" class="pause-btn">⏸️ 暂停</button>
                    <button id="nextBtn" class="next-btn">➡️ 下一个</button>
                </div>
                <button id="reviewDifficultBtn2" class="difficult-btn">📚 复习生词本</button>
                <button id="backBtn" class="back-btn">返回分组</button>
            </div>
        </div>

        <div id="difficultWordsView" class="view">
            <h1>生词本</h1>
            <div class="difficult-list" id="difficultList"></div>
            <div class="controls">
                <button id="backFromDifficultBtn" class="back-btn">返回主菜单</button>
                <button id="startReviewBtn" class="start-btn">开始复习生词</button>
            </div>
        </div>
    </div>

    <script>
        // 单词数据 - 你可以在这里添加你的4000个单词
        const wordData = {
            groups: {
                group1: {
                    name: "第1组 (1-10)",
                    words: [
                        { id: "1", word: "abandon", phonetic: "[əˈbændən]", meaning: "抛弃，放弃", sentence: "He abandoned his car and ran away." },
                        { id: "2", word: "ability", phonetic: "[əˈbɪləti]", meaning: "能力，才能", sentence: "She has the ability to speak three languages." },
                        { id: "3", word: "abroad", phonetic: "[əˈbrɔːd]", meaning: "在国外，到国外", sentence: "They are planning to study abroad next year." },
                        { id: "4", word: "academic", phonetic: "[ˌækəˈdemɪk]", meaning: "学术的，学院的", sentence: "She has a strong academic background." },
                        { id: "5", word: "accept", phonetic: "[əkˈsept]", meaning: "接受，同意", sentence: "I accept your apology." },
                        { id: "6", word: "access", phonetic: "[ˈækses]", meaning: "进入，使用权", sentence: "Students have access to the library." },
                        { id: "7", word: "accident", phonetic: "[ˈæksɪdənt]", meaning: "事故，意外", sentence: "He was injured in a car accident." },
                        { id: "8", word: "accompany", phonetic: "[əˈkʌmpəni]", meaning: "陪伴，伴随", sentence: "She accompanied me to the meeting." },
                        { id: "9", word: "accomplish", phonetic: "[əˈkʌmplɪʃ]", meaning: "完成，实现", sentence: "We accomplished our goal." },
                        { id: "10", word: "account", phonetic: "[əˈkaʊnt]", meaning: "账户，说明", sentence: "I have a bank account." }
                    ]
                },
                group2: {
                    name: "第2组 (11-20)", 
                    words: [
                        { id: "11", word: "beautiful", phonetic: "[ˈbjuːtɪfl]", meaning: "美丽的，漂亮的", sentence: "She has a beautiful smile." },
                        { id: "12", word: "benefit", phonetic: "[ˈbenɪfɪt]", meaning: "好处，益处", sentence: "Exercise has many health benefits." },
                        { id: "13", word: "business", phonetic: "[ˈbɪznəs]", meaning: "商业，生意", sentence: "He runs a successful business." },
                        { id: "14", word: "challenge", phonetic: "[ˈtʃælɪndʒ]", meaning: "挑战", sentence: "This job presents new challenges every day." },
                        { id: "15", word: "communication", phonetic: "[kəˌmjuːnɪˈkeɪʃn]", meaning: "沟通，交流", sentence: "Good communication is key to success." }
                    ]
                }
            }
        };

        // 应用主逻辑
        class WordLearningApp {
            constructor() {
                this.currentGroup = null;
                this.currentWordIndex = 0;
                this.currentPlayState = 0;
                this.isPlaying = false;
                this.autoPlay = true;
                this.currentTimeout = null;
                this.initializeApp();
            }

            initializeApp() {
                this.bindEvents();
                this.renderGroupSelection();
                this.checkLocalStorage();
            }

            bindEvents() {
                document.getElementById('reviewDifficultBtn').addEventListener('click', () => this.showDifficultWords());
                document.getElementById('reviewDifficultBtn2').addEventListener('click', () => this.showDifficultWords());
                document.getElementById('prevBtn').addEventListener('click', () => this.prevWord());
                document.getElementById('nextBtn').addEventListener('click', () => this.nextWord());
                document.getElementById('backBtn').addEventListener('click', () => this.showGroupSelection());
                document.getElementById('difficultBtn').addEventListener('click', () => this.toggleDifficultWord());
                document.getElementById('backFromDifficultBtn').addEventListener('click', () => this.showGroupSelection());
                document.getElementById('startReviewBtn').addEventListener('click', () => this.startDifficultReview());
                document.getElementById('pauseBtn').addEventListener('click', () => this.togglePause());
            }

            checkLocalStorage() {
                if (!localStorage.getItem('difficultWords')) {
                    localStorage.setItem('difficultWords', JSON.stringify([]));
                }
            }

            renderGroupSelection() {
                const groupList = document.getElementById('groupList');
                groupList.innerHTML = '';
                
                Object.entries(wordData.groups).forEach(([groupId, group]) => {
                    const groupItem = document.createElement('div');
                    groupItem.className = 'group-item';
                    groupItem.innerHTML = `
                        <div>${group.name}</div>
                        <small style="color: #666;">${group.words.length} 个单词</small>
                    `;
                    groupItem.addEventListener('click', () => this.startGroupLearning(groupId));
                    groupList.appendChild(groupItem);
                });
                
                const difficultWords = this.getDifficultWords();
                const reviewBtn = document.getElementById('reviewDifficultBtn');
                if (difficultWords.length > 0) {
                    reviewBtn.textContent = `复习生词本 (${difficultWords.length})`;
                    reviewBtn.style.display = 'block';
                } else {
                    reviewBtn.textContent = '复习生词本';
                    reviewBtn.style.display = 'none';
                }
                
                this.showView('groupSelection');
            }

            showGroupSelection() {
                this.clearTimeouts();
                this.currentGroup = null;
                this.currentWordIndex = 0;
                this.currentPlayState = 0;
                this.isPlaying = false;
                this.autoPlay = true;
                
                if ('speechSynthesis' in window) {
                    speechSynthesis.cancel();
                }
                
                this.renderGroupSelection();
            }

            startGroupLearning(groupId) {
                if (!wordData.groups[groupId]) {
                    alert('分组不存在！');
                    return;
                }
                
                this.currentGroup = groupId;
                this.currentWordIndex = 0;
                this.currentPlayState = 0;
                this.isPlaying = false;
                this.autoPlay = true;
                
                this.showView('learningView');
                this.updateProgress();
                this.updateDebugInfo();
                this.updateControlButtons();
                this.playCurrentWord();
            }

            async playCurrentWord() {
                if (this.isPlaying || !this.autoPlay) return;
                
                const word = this.getCurrentWord();
                if (!word) return;
                
                this.isPlaying = true;
                this.updateDebugInfo();
                this.updateControlButtons();
                
                try {
                    switch (this.currentPlayState) {
                        case 0:
                            this.showBlankView();
                            this.updateStateIndicator('🔊 第一遍发音...');
                            await this.speakWordWithTimeout(word.word);
                            if (this.autoPlay && this.isPlaying) {
                                this.currentPlayState = 1;
                                this.isPlaying = false;
                                this.currentTimeout = setTimeout(() => this.playCurrentWord(), 800);
                            }
                            break;
                        case 1:
                            this.showBlankView();
                            this.updateStateIndicator('🔊 第二遍发音...');
                            await this.speakWordWithTimeout(word.word);
                            if (this.autoPlay && this.isPlaying) {
                                this.currentPlayState = 2;
                                this.isPlaying = false;
                                this.currentTimeout = setTimeout(() => this.playCurrentWord(), 800);
                            }
                            break;
                        case 2:
                            this.showInfoView(word);
                            this.updateStateIndicator('🔊 第三遍发音并显示信息');
                            await this.speakWordWithTimeout(word.word);
                            if (this.autoPlay && this.isPlaying) {
                                this.currentPlayState = 3;
                                this.isPlaying = false;
                                this.updateStateIndicator('✅ 播放完成，自动继续');
                                this.currentTimeout = setTimeout(() => {
                                    if (this.autoPlay && !this.isPlaying) {
                                        this.nextWord();
                                    }
                                }, 2000);
                            }
                            break;
                    }
                } catch (error) {
                    this.isPlaying = false;
                    this.updateControlButtons();
                }
                this.updateProgress();
            }

            async speakWordWithTimeout(text) {
                return new Promise((resolve) => {
                    if ('speechSynthesis' in window) {
                        try {
                            speechSynthesis.cancel();
                            const utterance = new SpeechSynthesisUtterance(text);
                            utterance.lang = 'en-US';
                            utterance.rate = 0.8;
                            utterance.onend = resolve;
                            utterance.onerror = resolve;
                            setTimeout(() => speechSynthesis.speak(utterance), 100);
                        } catch (error) {
                            setTimeout(resolve, 2000);
                        }
                    } else {
                        setTimeout(resolve, 2000);
                    }
                });
            }

            showBlankView() {
                document.getElementById('blankView').classList.add('active');
                document.getElementById('infoView').classList.remove('active');
            }

            showInfoView(word) {
                document.getElementById('blankView').classList.remove('active');
                document.getElementById('infoView').classList.add('active');
                
                document.getElementById('currentWord').textContent = word.word;
                document.getElementById('currentPhonetic').textContent = word.phonetic;
                document.getElementById('currentMeaning').textContent = word.meaning;
                document.getElementById('currentSentence').textContent = word.sentence;
                
                const difficultBtn = document.getElementById('difficultBtn');
                if (this.isWordDifficult(word.id)) {
                    difficultBtn.textContent = '✅ 已标记为不熟悉';
                    difficultBtn.classList.add('active');
                } else {
                    difficultBtn.textContent = '标记为不熟悉';
                    difficultBtn.classList.remove('active');
                }
            }

            nextWord() {
                this.clearTimeouts();
                if ('speechSynthesis' in window) speechSynthesis.cancel();
                this.isPlaying = false;
                this.currentWordIndex++;
                this.currentPlayState = 0;
                if (this.currentWordIndex >= this.getCurrentGroupWords().length) {
                    alert('学习完成！');
                    this.showGroupSelection();
                    return;
                }
                this.playCurrentWord();
            }

            prevWord() {
                this.clearTimeouts();
                if ('speechSynthesis' in window) speechSynthesis.cancel();
                this.isPlaying = false;
                if (this.currentWordIndex > 0) this.currentWordIndex--;
                this.currentPlayState = 0;
                this.playCurrentWord();
            }

            togglePause() {
                this.autoPlay = !this.autoPlay;
                this.updateControlButtons();
            }

            updateControlButtons() {
                const pauseBtn = document.getElementById('pauseBtn');
                const prevBtn = document.getElementById('prevBtn');
                
                prevBtn.disabled = this.currentWordIndex === 0;
                pauseBtn.textContent = this.autoPlay ? '⏸️ 暂停' : '▶️ 继续';
            }

            toggleDifficultWord() {
                const word = this.getCurrentWord();
                if (!word) return;
                
                let difficultWords = this.getDifficultWords();
                if (this.isWordDifficult(word.id)) {
                    difficultWords = difficultWords.filter(id => id !== word.id);
                    document.getElementById('difficultBtn').textContent = '标记为不熟悉';
                    document.getElementById('difficultBtn').classList.remove('active');
                } else {
                    difficultWords.push(word.id);
                    document.getElementById('difficultBtn').textContent = '✅ 已标记为不熟悉';
                    document.getElementById('difficultBtn').classList.add('active');
                }
                localStorage.setItem('difficultWords', JSON.stringify(difficultWords));
            }

            showDifficultWords() {
                const difficultWords = this.getDifficultWords();
                const difficultList = document.getElementById('difficultList');
                difficultList.innerHTML = '';
                
                if (difficultWords.length === 0) {
                    difficultList.innerHTML = '<div style="text-align: center; color: #666; padding: 40px;">生词本为空</div>';
                    document.getElementById('startReviewBtn').style.display = 'none';
                } else {
                    document.getElementById('startReviewBtn').style.display = 'block';
                    difficultWords.forEach(wordId => {
                        const word = this.findWordById(wordId);
                        if (word) {
                            const wordItem = document.createElement('div');
                            wordItem.className = 'difficult-word-item';
                            wordItem.innerHTML = `
                                <div class="difficult-word-info">
                                    <div class="difficult-word">${word.word}</div>
                                    <div class="difficult-meaning">${word.meaning}</div>
                                </div>
                                <button class="remove-btn" onclick="app.removeFromDifficult('${word.id}')">移除</button>
                            `;
                            difficultList.appendChild(wordItem);
                        }
                    });
                }
                this.showView('difficultWordsView');
            }

            removeFromDifficult(wordId) {
                let difficultWords = this.getDifficultWords();
                difficultWords = difficultWords.filter(id => id !== wordId);
                localStorage.setItem('difficultWords', JSON.stringify(difficultWords));
                this.showDifficultWords();
            }

            startDifficultReview() {
                const difficultWords = this.getDifficultWords();
                if (difficultWords.length === 0) return;
                
                this.currentGroup = 'difficult_review';
                this.currentWordIndex = 0;
                this.currentPlayState = 0;
                
                if (!wordData.groups.difficult_review) {
                    wordData.groups.difficult_review = { name: "生词复习", words: [] };
                }
                wordData.groups.difficult_review.words = difficultWords.map(id => this.findWordById(id)).filter(Boolean);
                
                this.showView('learningView');
                this.playCurrentWord();
            }

            clearTimeouts() {
                if (this.currentTimeout) clearTimeout(this.currentTimeout);
            }

            getCurrentGroupWords() { 
                if (this.currentGroup === 'difficult_review') {
                    return wordData.groups.difficult_review?.words || [];
                }
                return wordData.groups[this.currentGroup]?.words || []; 
            }
            
            getCurrentWord() { 
                return this.getCurrentGroupWords()[this.currentWordIndex]; 
            }
            
            findWordById(wordId) {
                for (const group of Object.values(wordData.groups)) {
                    const word = group.words.find(w => w.id === wordId);
                    if (word) return word;
                }
                return null;
            }
            
            getDifficultWords() { 
                return JSON.parse(localStorage.getItem('difficultWords') || '[]');
            }
            
            isWordDifficult(wordId) { 
                return this.getDifficultWords().includes(wordId); 
            }

            updateStateIndicator(text) {
                document.getElementById('stateIndicator').textContent = text;
            }

            updateProgress() {
                const words = this.getCurrentGroupWords();
                const progress = ((this.currentWordIndex + 1) / words.length) * 100;
                document.getElementById('progressFill').style.width = `${progress}%`;
                document.getElementById('progressText').textContent = `${this.currentWordIndex + 1}/${words.length}`;
            }
            
            updateDebugInfo() {
                const stateText = ['第一遍', '第二遍', '第三遍', '完成'][this.currentPlayState] || '准备中';
                document.getElementById('debugState').textContent = stateText;
            }
            
            showView(viewName) {
                document.querySelectorAll('.view').forEach(view => view.classList.remove('active'));
                document.getElementById(viewName).classList.add('active');
            }
        }

        const app = new WordLearningApp();
        window.app = app;
    </script>
</body>
</html>